package main

import (
	"github.com/iris-contrib/middleware/cors"
	"github.com/kataras/iris"
	"github.com/kataras/iris/core/router"
	"github.com/kataras/iris/middleware/logger"
	"go_oauth2/config"
	"go_oauth2/controllers"
	"go_oauth2/database"
	"go_oauth2/store"
)

func newApp() (oauthApp *iris.Application) {
	oauthApp = iris.New()
	oauthApp.Use(logger.New())

	// 配置保存token存储
	storeType := config.Config.Get("store.type").(string)
	store.NewStore(storeType)

	oauthApp.OnErrorCode(iris.StatusNotFound, func(ctx iris.Context) {
		_, _ = ctx.JSON(controllers.ApiResource(false, nil, "404 Not Found！"))
	})
	oauthApp.OnErrorCode(iris.StatusInternalServerError, func(ctx iris.Context) {
		_, _ = ctx.WriteString("Oup something went wrong, try again！")
	})

	iris.RegisterOnInterrupt(func() {
		_ = database.DB.Close()
	})

	crs := cors.New(cors.Options{
		AllowedOrigins:   []string{"*"}, // allows everything, use that to change the hosts.
		AllowedMethods:   []string{"PUT", "PATCH", "GET", "POST", "OPTIONS", "DELETE"},
		AllowedHeaders:   []string{"*"},
		ExposedHeaders:   []string{"Accept", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization"},
		AllowCredentials: true,
	})

	v1 := oauthApp.Party("/v1", crs).AllowMethods(iris.MethodOptions)
	{
		v1.PartyFunc("/oauth", func(oauth router.Party) {
			// 根据账号密码获取access_token
			oauth.Post("/access_token", controllers.AccessToken)
			// 根据refresh_token刷新access_token或者重新获取access_token
			oauth.Post("/refresh_token", controllers.RefreshToken)
			// 根据access_token校验用户是否登录
			oauth.Post("/check_token", controllers.Check)
			// 根据access_token取消授权
			oauth.Post("cancel_token", controllers.Cancel)
		})
	}

	return
}

func main() {
	app := newApp()
	addr := config.Config.Get("app.addr").(string)
	_ = app.Run(iris.Addr(addr))
}
